import subprocess
import time


def _run_command(cmd, echo=True, check=True) -> str:
    if echo:
        print(cmd)
    cp = subprocess.run(cmd, shell=True, capture_output=True,
                        encoding="utf=-8", check=check)
    return cp.stdout


def command_devices() -> list[str]:
    devices = []
    for line in _run_command("hdc list targets", echo=False).splitlines():
        devices.append(line)
    return devices


def command_shellcmd(device: str, cmd: str, echo=True) -> None:
    _run_command("hdc -t {} shell {}".format(device, cmd))


def command_reboot(device):
    command_shellcmd(device, "reboot")


def command_remount(device):
    command_shellcmd(device, "mount -o rw,remount /")


def command_push(device, local, remote):
    _run_command("hdc -t {} file send {} {}".format(device, local, remote))


def command_pull(device, remote, local):
    _run_command("hdc -t {} file recv {} {}".format(device, remote, local))


def command_persistent_log(device):
    output = _run_command("hdc -t {} shell hilog -w query".format(device))
    try:
        output.index("zlib /data/log/hilog/hilog 512.0K 100")
    except:
        command_shellcmd(device, "hilog -w stop")
        command_shellcmd(device, "hilog -w start -l 512K -m zlib -n 100")
    else:
        print("log persistence task already start, just skip")


def timestamp(hint: str) -> None:
    ts = time.strftime("%Y-%m-%d %H:%M:%S")
    print("{} at {}".format(hint, ts))
